import React, { useEffect, useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { Divider, ScrollView, Text, useToast, View } from 'native-base';
import { Dimensions, StatusBar, TouchableOpacity } from 'react-native';
import { FasterImageView } from '@candlefinance/faster-image';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import ImageViewing from 'react-native-image-viewing';
import { useAsyncEffect, useReactive } from 'ahooks';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import Tools from '../../../utils/Tools.ts';
import RenderPrice from '../merchantProduct/component/RenderPrice.tsx';
import { ShowSkuSelectionPopup } from '../component/SkuSelectionPopup.tsx';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { updateShoppingCart } from '../../../redux/reducers/app.ts';
import RenderingDiscount from '../merchantProduct/component/RenderingDiscount.tsx';
import HomeRequest from '../../../request/homeRequest.ts';
import ShoppingCart from '../component/ShoppingCart.tsx';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { WebView } from 'react-native-webview';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { ShowSkuPackageSelectionPopup } from '../component/SkuPackageSelectionPopup.tsx';
import to from '../../../utils/to.ts';

interface IProductDetailsProps {
  navigation: NavigationProp<any, 'productDetails'>;
  route: RouteProp<{ productDetails: { product: IProductInformation; hasAddedToCart?: boolean } }, 'productDetails'>;
}
interface IState {
  imageViewingShow: boolean;
  shoppingCartProduct?: IProductInformation;
  product: IProductInformation;
  webViewHeight: number;
  shoppingCartVisible: boolean;
}
const windowWidth = Dimensions.get('window').width;

const ProductDetails: React.FC<IProductDetailsProps> = ({ navigation, route }) => {
  const insets = useSafeAreaInsets();
  const shoppingCart = useSelector((state: RootState) => state.shoppingCart);
  const state = useReactive<IState>({ imageViewingShow: false, product: route.params!.product, webViewHeight: 0, shoppingCartVisible: false });
  const dispatch = useDispatch<AppDispatch>();
  const toast = useToast();

  useAsyncEffect(async () => {
    if (route.params!.product) {
      Loading.show();
      state.product = route.params.product;
      const [err, res] = await to(HomeRequest.ObtainProductDetails({ id: state.product.goodsId }));
      if (err) {
        Loading.hide();
        return;
      }
      if (route.params.hasAddedToCart) {
        if (Tools.renderProductValidation(route.params.product) === 3) {
          ShowSkuSelectionPopup.show(route.params.product);
        } else {
          dispatch(updateShoppingCart({ type: 'add', data: route.params.product }));
          state.shoppingCartVisible = true;
        }
      }
      state.product = { ...state.product, ...res.data, active: state.product.active };
      Loading.hide();
    }
  }, [route.params]);

  useEffect(() => {
    state.shoppingCartProduct = shoppingCart.find((_item) => _item.goodsId === state.product.goodsId);
  }, [shoppingCart]);

  // 添加产品购物车
  const handleOperationProductToShoppingCart = (type: 'add' | 'remove', data: IProductInformation) => {
    dispatch(updateShoppingCart({ type, data }));
  };

  // 收藏或者取消收藏产品
  const handleCollectOrCancelProd = () => {
    Loading.show();
    const { goodsId, collect } = state.product;
    HomeRequest.CollectOrCancelProd({ state: collect ? 0 : 1, goodsId, collectType: 1 })
      .then(() => {
        toast.show({ description: collect ? '取消收藏成功' : '收藏成功' });
        state.product = { ...state.product, collect: collect ? 0 : 1 };
        Loading.hide();
      })
      .catch(() => {
        Loading.hide();
      });
  };

  return (
    <React.Fragment>
      <StatusBar translucent backgroundColor={'transparent'} barStyle="dark-content" />
      <View flex={1} bg={'#f7f5f5'}>
        <ScrollView flex={1} contentContainerStyle={{ flexGrow: 1 }} nestedScrollEnabled={true}>
          <View width={'100%'} height={300}>
            <Touchable style={{ flex: 1 }} onPress={() => (state.imageViewingShow = true)}>
              <FasterImageView style={{ flex: 1 }} source={{ url: state.product.mainImage, transitionDuration: 0.3, resizeMode: 'cover', cachePolicy: 'discWithCacheControl', showActivityIndicator: true, borderRadius: 8 }} />
            </Touchable>
          </View>
          <View px={4} py={4} bg={'white'} marginBottom={2}>
            <View flexDirection={'row'} justifyContent={'space-between'} alignItems={'center'}>
              <Text fontSize={18} fontWeight={'bold'}>
                {state.product.name}
              </Text>
              <View>
                <AntDesign onPress={handleCollectOrCancelProd} name={state.product.collect > 0 ? 'star' : 'staro'} color={state.product.collect > 0 ? CommonStyle.mainColor : ''} size={22} />
                <Text fontSize={8} color={CommonStyle.deepGrey}>
                  收藏
                </Text>
              </View>
            </View>
            <View mt={2}>{RenderingDiscount(state.product, shoppingCart)}</View>
            <View mt={2} flexDirection={'row'} justifyContent={'space-between'} alignItems={'center'}>
              <View flexDirection={'row'} alignItems={'center'}>
                {Tools.renderProductValidation(state.product) > 2 && RenderPrice(state.product, shoppingCart, 14)}
                {state.product.packageFee > 0 && (
                  <Text ml={2} fontSize={12} color={CommonStyle.deepGrey}>
                    包装费：¥ {state.product.packageFee}
                  </Text>
                )}
              </View>
              <View>
                {Tools.renderProductValidation(state.product) <= 2 && (
                  <View flex={1} width={'100%'} flexDirection={'row'} justifyContent={'space-between'}>
                    <View />
                    <Text paddingX={2} fontSize={13} textAlign={'right'} color={CommonStyle.deepGrey}>
                      {Tools.renderProductValidation(state.product) === 1 ? '非可售时间' : '已售罄'}
                    </Text>
                  </View>
                )}
                {Tools.renderProductValidation(state.product) === 3 && (
                  <TouchableOpacity
                    onPress={() => {
                      if (state.product.goodsType === 2) {
                        ShowSkuPackageSelectionPopup.show(state.product);
                      } else {
                        ShowSkuSelectionPopup.show(state.product);
                      }
                    }}
                  >
                    <View backgroundColor={CommonStyle.mainColor} borderRadius={8}>
                      <Text paddingX={2} fontSize={13} color={'#fff'}>
                        选规格
                      </Text>
                    </View>
                  </TouchableOpacity>
                )}
                {Tools.renderProductValidation(state.product) === 4 && (
                  <View flexDirection={'row'}>
                    {state.shoppingCartProduct && (
                      <>
                        <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('remove', state.product)}>
                          <Ionicons name={'remove-circle'} size={26} color={CommonStyle.mainColor} />
                        </TouchableOpacity>
                        <Text mx={2}>{state.shoppingCartProduct.nums}</Text>
                      </>
                    )}
                    <TouchableOpacity onPress={() => handleOperationProductToShoppingCart('add', state.product)}>
                      <Ionicons name={'add-circle'} size={26} color={CommonStyle.mainColor} />
                    </TouchableOpacity>
                  </View>
                )}
              </View>
            </View>
          </View>
          <View px={4} py={4} bg={'white'}>
            <View flexDirection={'row'} mb={2}>
              <Text style={{ width: 90 }} color={CommonStyle.deepGrey}>
                商户名称：
              </Text>
              <Text flex={1}>{state.product.businessName}</Text>
            </View>
            <View flexDirection={'row'} mb={2}>
              <Text style={{ width: 90 }} color={CommonStyle.deepGrey}>
                商品分类：
              </Text>
              <Text flex={1}>{state.product.thirdClassifyName}</Text>
            </View>
            <View flexDirection={'row'} mb={2}>
              <Text style={{ width: 90 }} color={CommonStyle.deepGrey}>
                简介：
              </Text>
              <Text flex={1}>{state.product.introduce}</Text>
            </View>
            <View flexDirection={'row'} mb={2}>
              <Text style={{ width: 90 }} color={CommonStyle.deepGrey}>
                商家咨询：
              </Text>
              <TouchableOpacity style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }} onPress={() => Tools.callPhone(state.product.businessPhone)}>
                <Text color={CommonStyle.price} mr={2}>
                  拨打电话
                </Text>
                <FontAwesome name={'phone'} size={16} color={CommonStyle.price} />
              </TouchableOpacity>
            </View>
            {state.product.goodsHours && state.product.goodsHours.length > 0 && (
              <View flexDirection={'row'}>
                <Text style={{ width: 90 }} color={CommonStyle.deepGrey}>
                  可售时间：
                </Text>
                <View>
                  {state.product.goodsHours.map((item, index) => {
                    return (
                      <Text color={CommonStyle.price} key={index}>
                        {item.beginHours}-{item.endHours}
                      </Text>
                    );
                  })}
                </View>
              </View>
            )}
          </View>
          {state.product.describes && (
            <>
              <View px={4} py={4} flexDirection={'row'} alignItems={'center'}>
                <Divider width={'40%'} />
                <Text flex={1} textAlign={'center'}>
                  详情
                </Text>
                <Divider width={'40%'} />
              </View>
              {state.product.describes && (
                <View px={4} py={4} bg={'white'} marginBottom={2}>
                  <WebView
                    style={{ height: state.webViewHeight, width: windowWidth - 32 }}
                    source={{ uri: `https://kics.kanglailab.com/richText?text=${encodeURIComponent(state.product.describes)}` }}
                    onMessage={(event) => {
                      const height = parseInt(event.nativeEvent.data, 10);
                      if (!isNaN(height) && height !== state.webViewHeight) {
                        state.webViewHeight = height;
                      }
                      Loading.hide();
                    }}
                    onLoad={() => Loading.hide()}
                    onError={() => Loading.hide()}
                  />
                </View>
              )}
            </>
          )}
        </ScrollView>
        <View position={'absolute'} left={4} style={[{ paddingTop: insets.top + 22 }]}>
          <AntDesign name={'arrowleft'} size={24} color={'black'} style={{ marginRight: 12 }} onPress={() => navigation.goBack()} />
        </View>
      </View>
      <ShoppingCart visible={state.shoppingCartVisible} />
      <ImageViewing images={[{ uri: state.product.mainImage }]} imageIndex={0} visible={state.imageViewingShow} onRequestClose={() => (state.imageViewingShow = false)} />
    </React.Fragment>
  );
};

export default ProductDetails;
